--
-- @Author:      name
-- @DateTime:    2018-03-30 23:05:48
-- @Description: 机器人管理

local skynet = require "skynet"
local log = require "Log"
local Network = require "Network"

local roomConfig = require "lua_NiuniuTableList"
local common = require "common"
local NodeMessage = require "NodeMessage"
require "util"
require "setting"

local Manager = class("Manager")

---------------------------------------------------------
-- Private
---------------------------------------------------------
function Manager:ctor(message)	
	--随机种子
    local time = tostring(os.time())
    math.randomseed(time:reverse():sub(1, 7))	
	local svrConfig = robot_backstage	
	self.msg = message
	self.ip = svrConfig.ip
	self.port = svrConfig.port
	self.tbRobot = { name="usergame", pk='uid',key='uid', indexkey='' }
	self.tbUser = { name="fwqp_user", pk='mid',key='mid', indexkey='' }
	self.tbConf = {} --场次配置
	for _,v in pairs(roomConfig) do 
		table.insert(self.tbConf,v)
	end
	table.sort(self.tbConf,function (a,b)
		if a.min_coin < b.min_coin then 
			return true
		end
	end)
	self.tbAddMoney = {20,255,1500,2301,3000}

	self.nodeMessage = NodeMessage.new()

	--数据库服务 
	local mysqldata = {host = skynet.getenv("mysql_host"),
				  port = skynet.getenv("mysql_port"),				  
				  user = skynet.getenv("mysql_user"),
				  password = skynet.getenv("mysql_pwd"),
				  database = skynet.getenv("mysql_db"),
				  serviceName = "mysql_service",
				 }
	self.mysql = skynet.newservice("mysql_service")
	skynet.call(self.mysql, "lua", "start", mysqldata)


	-- self.redis = skynet.uniqueservice("redis_service")
	-- skynet.call(self.redis, "lua", "start")

	--机器人服务
	self.tbService = {}
	self.tbPlayer = {}
	local svrname = skynet.getenv("robot_name")
	self.svrname = svrname
	if svrname == 'allgame' then 
		local name 
		local config
		for k,v in pairs(robot_setting) do 
			name = k
			config = v
			self.tbService[v.gameid] = skynet.uniqueservice(name)
			self.tbPlayer[v.gameid] = v.player
		end
	else
		local gameid = robot_setting[svrname].gameid	
		self.gameid = gameid
		self.tbService[gameid] = skynet.uniqueservice(svrname)		
		self.tbPlayer[gameid] = robot_setting[svrname].player		
	end

	--开启网络模块
	self.network = Network.new(self.ip,self.port)

	-- local netTest = Network.new(self.ip,5200)
	-- local data = {
	-- 	web_test={
	-- 		a=1,
	-- 		b=2,
	-- 	}
	-- }
	-- netTest:sendJson(data)
	--注册消息回调
	self:register()
	self:startRobot()
end

function Manager:register()
	self.network:register('rb_nt_add',handler(self,self.addRobot))

	self.msg:registerSelf('change_money',handler(self,self.changeMoney))	
end

--加载表数据
function Manager:loadData(tableInfo, field)
	local tbname = tableInfo.name
	local pk = tableInfo.pk
	local key = tableInfo.key
	local offset = 0
	local sql
	local data = {}
	if not field then
		sql = string.format("select * from %s order by %s asc limit %d, 1000", tbname, pk, offset)
	else
		sql = string.format("select * from %s where "..key.." = %d order by %s asc limit %d, 1000", tbname, field, pk, offset)
	end
	local rs = skynet.call(self.mysql, "lua", "execute", sql)
	if #rs <= 0 then 
		print("____机器人表为空___")
		return data
	end
	for _, row in pairs(rs) do
		table.insert(data, row)			
	end
	return data
end

--
function Manager:laodUser(playerid)
	return call_redis({ "hgetall", self.tbUser.name .. ":" .. playerid }, playerid)
end


function Manager:startRobot()	
	--机器人表
	local data = self:loadData(self.tbRobot)
	self.robotData = data
	local tbNum = {22,23,3,3}
	local tbOnline = {0,0,0,0}
	local num = 0
	local onlineNum = 0
	local tbUser
	local users
	local user
	local roomType --要入的场
	local gameid
	local tbNotOnline = {}
	-- print(data)

	if self.svrname == 'paodekuai' then 
		data = {
			{mid=5000113,type=1,robotgameid=103},
			{mid=5000114,type=1,robotgameid=103},
			{mid=5000115,type=1,robotgameid=103},
			
			{mid=5000116,type=2,robotgameid=103},
			{mid=5000117,type=2,robotgameid=103},
		}
	end
	print("---------self.svrname ", self.svrname )
	if self.svrname == 'zhongfabai' then		
		data = {
			--{mid=5000115,type=1,robotgameid=109},
		}
		
	end
	if self.gameid then 
		for k,v in pairs(self.tbPlayer[self.gameid]) do 
			num = num + v
		end		
	else
		for k,v in pairs(self.tbPlayer) do 
			for _,n in pairs(v) do 
				num = num + n
			end
		end
	end
	for k,v in pairs(data) do
		-- print("___k,v",k,v)
		gameid = v.robotgameid
		self.nodeMessage:sendService(self.tbService[gameid], "add_robot", v)	
	end
	

	-- skynet.fork(function()
	-- 	while (true) do 	
	-- 		mix_array(data)
	-- 		onlineNum = 0
	-- 		tbNotOnline = {}
	-- 		tbOnline = {}
	-- 		for k,v in pairs(data) do				
	-- 			user = self:laodUser(v.mid)
	-- 			if not v.robotgameid then v.robotgameid = 101 end
	-- 			roomType = v.type
	-- 			gameid = v.robotgameid 
	-- 			if not tbOnline[gameid] then 
	-- 				tbOnline[gameid] = {0,0,0,0}
	-- 			end				
	-- 			if not user.mid then 
	-- 				users = self:loadData(self.tbUser,v.mid)
	-- 				user = users[1] or {}
	-- 			end
	-- 			-- print(user.mid,user.diamond,user.online,type(user.online),"_________________",v.mid)
	-- 			if user.mid and user.status and tonumber(user.status) == 0 then 					
	-- 				--未上线
	-- 				if tonumber(user.online) == 1 then 
	-- 					if self.svrname == 'allgame' then 														
	-- 						onlineNum = onlineNum + 1
	-- 					elseif self.gameid == gameid then 
	-- 						onlineNum = onlineNum + 1
	-- 					end
	-- 					tbOnline[gameid][roomType] = tbOnline[gameid][roomType] + 1
	-- 					-- print("___roomType",gameid,roomType,tbOnline[gameid][roomType],user.mid)
	-- 				else
	-- 					table.insert(tbNotOnline,v)
	-- 				end		
	-- 				-- print("___Robot_222222________",k,user.mid,user.diamond,onlineNum,num)
	-- 				if num <= onlineNum then 
	-- 					break
	-- 				end
	-- 			end
	-- 			skynet.sleep(5)
	-- 		end
	-- 		print("_____tbOnline__",tbOnline)
	-- 		-- if tbOnline[101] then 
	-- 		-- 	print("___roomType",tbOnline[101][1],self.tbPlayer[101][1])
	-- 		-- end
	-- 		for k,v in pairs(tbNotOnline) do
	-- 			roomType = v.type
	-- 			gameid = v.robotgameid 
	-- 			-- print("____tbOnline[gameid]___",tbOnline[gameid],gameid,roomType)
	-- 			if self.tbPlayer[gameid] and tbOnline[gameid][roomType] < self.tbPlayer[gameid][roomType] then 
	-- 				tbOnline[gameid][roomType] = tbOnline[gameid][roomType] + 1
	-- 				skynet.send(self.tbService[gameid], "lua", "add_robot", v)	
	-- 				skynet.sleep(math.random(50,200))
	-- 			end
	-- 		end
	-- 		skynet.sleep(30*100)
	-- 	end
		
	-- end)
end


function Manager:addRobot(data)
	print("____addRobot_____")
	-- local data = self:loadData()
	-- print(data)
end

function Manager:changeMoney(data)
	print("_________data__",data)
	local playerid = data.playerid
	local robotType = data.robotType
	--金币不够入处理			
	local data = {
		rb_change_money_req={
			playerid = playerid,
			diamond = self.tbAddMoney[robotType],
			}
		}
	self.network:send(data)
	print("___addmoney___________",data)	

end
return Manager